package com.lc.datasource;

import com.lc.config.annos.Autowired;
import com.lc.config.annos.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author liuc
 * @date 2021/4/19
 * @description
 **/
@Component
public class DataSourceContext {

    @Autowired
    private MyDataSource dataSource;

    private ThreadLocal<Connection> dataSourceThreadLocal = new InheritableThreadLocal<>();

    public Connection getConnection() throws SQLException {
        if(dataSourceThreadLocal.get() != null) return dataSourceThreadLocal.get();
        Connection connection = dataSource.getConnection();
        dataSourceThreadLocal.set(connection);
        return connection;
    }
}
